import os
import webapp2
import cgi
import logging
import urllib
import jinja2

from django.utils import simplejson
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers


from models.beer import Beer
from models.brewery import Brewery


jinja_environment = jinja2.Environment(
	loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

def beer_key(beer_name =None):
	return db.Key.from_path('Beer', beer_name)

################
class BeerHandler(webapp2.RequestHandler):

	def get(self):
		tag = self.request.get('id')
		if (tag):
			if (tag == 'all'):
				output = []
				beers = Beer.all().order('name')
				for br in beers:
					output.append(br.to_dict())
				self.response.out.write(simplejson.dumps({'beers' : output}).replace("\/", "/"))
			else:
				output = []
				bId = int(tag)
				if (bId > 0):
					br = Beer.get_by_id(bId)
					if br != None:
						output.append(br.to_dict())
				self.response.out.write(simplejson.dumps({'beers' : output}).replace("\/", "/"))
		else:
			
			output = []
			beers = Beer.all().order('name')
			for br in beers:
				output.append(br.to_dict())
			self.response.out.write(simplejson.dumps({'beers' : output}).replace("\/", "/"))
			
			
################
class AddBeerHandler(webapp2.RequestHandler):
	
	def get(self):
		
		beer_names = '<option selected="selected" value="">---------</option>'
		for bn in Beer.all().order('name'):
			beer_names += '<option value=" '
			beer_names += str(bn.key())
			beer_names += ' \"> '
			beer_names += str(bn.name)
			beer_names += ' </option> '
		
		
		beer_images = '<option selected="selected" value="">---------</option>'
		for b in blobstore.BlobInfo.all().order('filename'):
			beer_images += '<option value=" '
			beer_images += str(b.key())
			beer_images += ' \"> '
			beer_images += str(b.filename)
			beer_images += ' </option> '
			
		brewery_list = '<option selected="selected" value="">---------</option>'
		breweries = Brewery.all().order('name')
		for brwy in breweries:
			brewery_list += '<option value=" '
			brewery_list += str(brwy.key().id())
			brewery_list +=	 ' \"> '
			brewery_list += brwy.name
			brewery_list +=	 ' </option> '
		
		self.response.out.write("""
			<html>
			<body>
			<legend>Add New Beer</legend>
			""")
		self.response.out.write( """
			<script src="http://code.jquery.com/jquery-1.8.3.min.js">
			</script>

			<SCRIPT LANGUAGE="javascript">
			$(document).ready(function() {
				$('#select_brewery').change(function() {
					$('input[name="selected_brewery"]').val($(this).val());
				});
			});
			</SCRIPT>
			<SCRIPT LANGUAGE="javascript">
			$(document).ready(function() {
				$('#select_beer_name').change(function() {
					$('input[name="beer_name"]').val($('#select_beer_name').text());
				});
			});
			</SCRIPT>
			<SCRIPT LANGUAGE="javascript">
			$(document).ready(function() {
				$('#select_image').change(function() {
					$('input[name="selected_image"]').val($(this).val());
				});
			});
			</SCRIPT>
			""" )
		self.response.out.write('<form name="beer_form" action="/upload" method="post">')
		self.response.out.write("""
			<div id="beer"><label>Beer Name: </label>""")
		#<select id="select_beer_name"> 
		#self.response.out.write(beer_names)
		#self.response.out.write('</select>')
		self.response.out.write(""" <input type="text" name="beer_name" /></div>
			<div id="brewery"><label>Brewery: </label>
			<select id = "select_brewery" name="brewery"> """)
		self.response.out.write(brewery_list)
		self.response.out.write('</select>')
		self.response.out.write(""" <input type="text" name="selected_brewery" size="3" />		 
			<div>Description: <input type="text" name="beer_desc" size="100"/></div>
			<div>ABV<input type="text" name="beer_abv" /> IBU<input type="text" name="beer_ibu" /></div>
			<div id="beer_image"><label>Beer Image: </label>
			<select id="select_image"> """)
		self.response.out.write(beer_images)
		self.response.out.write('</select>')
		self.response.out.write(""" <input type="text" name="selected_image" size="15" />
			
			</div>

			<div></div>
			""")

		#self.response.out.write("""  BEER STYLES DROPDOWN """)

		self.response.out.write("""
			<div><input type="submit" value="Add Beer"></div>
			<div> Current Beers </div>
			
			</form>""")
		for bn in Beer.all().order('name'):
			self.response.out.write(bn.name)
			self.response.out.write('<br />')

		self.response.out.write('</body></html>')
		
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):

	def post(self):
		logger = logging.getLogger('brewery_app')
		logger.setLevel(logging.DEBUG)
		beer_name = cgi.escape(self.request.get('beer_name'))
		brwy_selected = cgi.escape(self.request.get('selected_brewery'))
		brwy_name = Brewery.get_by_id(int(brwy_selected)).name
		beer_abv = cgi.escape(self.request.get('beer_abv'))
		beer_ibu = cgi.escape(self.request.get('beer_ibu'))
		#beer_style = cgi.escape(self.request.get('beer_style'))
		beer_desc = cgi.escape(self.request.get('beer_desc'))
		beer_image = cgi.escape(self.request.get('selected_image'))
		
		logger.info('Brewery: ' + brwy_name)
		logger.info(brwy_selected)
		logger.debug('Selected Brewery: ' + brwy_selected)

		br = Beer.all().filter('name =', beer_name).get()	
		if not br:			
			br = Beer()
			br.name = beer_name
		if brwy_selected != '':
			br.brewery_id = int(brwy_selected)
			br.brewery_name = brwy_name
		if beer_desc != '':
			br.description = beer_desc
		if beer_abv != '':
			br.abv = float(beer_abv)
		if beer_ibu != '':
			br.ibu = float(beer_ibu)
		if beer_image != '':
			br.image = beer_image
		
		br.put()
		newbr = Beer.all().filter('name =', beer_name).get()
		brid = newbr.key().id()
		self.redirect('/beers?id=' + str(brid))
		#else:
		#	self.response.out.write("<html><body><p>An Error Occured</p></body></html>")
		self.redirect('/beers')

class ImageUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
	def post(self):
		upload_files = self.get_uploads('file')	 # 'file' is file upload field in the form
		blob_info = upload_files[0]
		self.redirect('/beers/images')
		
class ImageHandler(webapp2.RequestHandler):
	def get(self):
		upload_url = blobstore.create_upload_url('/imageupload')
		self.response.out.write('<html><body>')
		self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
		self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""")

		for b in blobstore.BlobInfo.all().order('filename'):
			self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')	
		
class BeerListHandler(webapp2.RequestHandler):

	#CHANGE to be a nice page listing beers.  (including beer name brewery.....)
	def get(self):
		self.response.out.write("""
			<html>
			<body>
			""")
		self.response.out.write("""
			<h1>Beer Image List</h1>
			""")
		for b in blobstore.BlobInfo.all():
			self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')
		self.response.out.write("""
			</body>
			</html>
			""")
	
## Class that retreives the beer image and displays on screen
## NEED to change or add new to support retrieval by Android.
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
	blob_key = str(urllib.unquote(resource))
	if not blobstore.get(blob_key):
		self.error(404)
	else:
		self.response.out.write("""
			<html>
			<head>
			<meta charset="utf-8">
				<title>KegDroid</title>
			</head>
			<body>
			""")
		beerImage = blobstore.BlobInfo.get(blob_key)
		self.send_blob(beerImage)
		self.response.out.write("""
			</body>
			</html>
			""")

app = webapp2.WSGIApplication([
	('/beers/add', AddBeerHandler),
	('/upload', UploadHandler),
	('/imageupload', ImageUploadHandler),
	('/beers/images', ImageHandler),
	('/serve/([^/]+)?', ServeHandler),
	('/beers/list', BeerListHandler),
	('/beers', BeerHandler)

], debug=True)
